/**
 * 
 */
package com.jquery.ui.core.freemarker;

import java.io.File;


import java.util.Map;

import javax.servlet.jsp.JspWriter;

import com.jquery.ui.core.exception.JqueryUIRuntime;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * @author linyajun
 * 
 * @date	2013-9-18
 * @description   
 */
public final class FreemarkerFactory {

	private static FreemarkerFactory factory;
	private  Configuration config;
	private FreemarkerFactory(){
		
		try {
			config=new Configuration();
			config.setDirectoryForTemplateLoading(new File(FreemarkerFactory.class.getClassLoader().getResource("com/jquery/ui/tags/templates").toURI()));
			config.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			
			e.printStackTrace();
			throw new JqueryUIRuntime(e);
		} 
		
		
	}
	public static FreemarkerFactory getInstance(){
		if (factory==null) {
			factory=new FreemarkerFactory();
			
		}
		
		return factory;
	}
	
	/**
	 * @param templateName
	 * @param attribut
	 * @param out
	 * @description   渲染模板
	 */
	public  void renderTemplate(String templateName,Map<String, Object> attribut,JspWriter out){
		try {
			Template template=config.getTemplate(templateName,"UTF-8");
			template.setAutoFlush(true);
			template.process(attribut, out);		
			out.flush();
		} catch (Exception e) {			
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
	}
	/**
	 * @param templateName
	 * @param attribut
	 * @param out
	 * @description   渲染模板
	 */
	public  void renderTemplate(String templateName,JspWriter out){
		try {
			
			
			Template template=config.getTemplate(templateName,"UTF-8");
			template.setAutoFlush(true);
			template.process(null, out);
		} catch (Exception e) {			
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
	}
}
